//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_recycle_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/bulletin_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/idea_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/issue_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/project_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/project_entry_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/requirement_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/testcase_dao"
	"atomgit.com/openlinksaas-org/api-server/utils"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_idea_api"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_recycle_api"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *ProjectRecycleApiImpl) Recover(ctx context.Context, req *project_recycle_api.RecoverRequest) (*project_recycle_api.RecoverResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_recycle_api.RecoverResponse{
			Code:   project_recycle_api.RecoverResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_recycle_api.RecoverResponse{
			Code:   project_recycle_api.RecoverResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_recycle_api.RecoverResponse{
			Code:   project_recycle_api.RecoverResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	if projectItem.Closed {
		return &project_recycle_api.RecoverResponse{
			Code:   project_recycle_api.RecoverResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	if !(projectItem.OwnerUserId == sessionItem.UserId || roleItem.BasicInfo.Admin) {
		return &project_recycle_api.RecoverResponse{
			Code:   project_recycle_api.RecoverResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	recycleItem, err := project_dao.RecycleDao.Get(ctx, req.ProjectId, req.RecycleItemId)
	if err != nil {
		return &project_recycle_api.RecoverResponse{
			Code:   project_recycle_api.RecoverResponse_CODE_NO_RECYCLE_ITEM,
			ErrMsg: "相关对象不存在",
		}, nil
	}

	title, err := apiImpl.getTitle(ctx, req.ProjectId, req.RecycleItemId, project_recycle_api.RECYCLE_ITEM_TYPE(recycleItem.RecycleItemType))
	if err != nil {
		return nil, err
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(context.Background(), func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = project_dao.RecycleDao.Remove(sessCtx, req.ProjectId, req.RecycleItemId)
		if err != nil {
			return nil, err
		}
		if recycleItem.RecycleItemType == uint32(project_recycle_api.RECYCLE_ITEM_TYPE_RECYCLE_ITEM_IDEA) {
			err = apiImpl.recoverIdea(sessCtx, projectItem, recycleItem.RecycleItemId)
			if err != nil {
				return nil, err
			}
		} else if recycleItem.RecycleItemType == uint32(project_recycle_api.RECYCLE_ITEM_TYPE_RECYCLE_ITEM_REQUIREMENT) {
			err = apiImpl.recoverRequirement(sessCtx, projectItem, recycleItem.RecycleItemId)
			if err != nil {
				return nil, err
			}
		} else if recycleItem.RecycleItemType == uint32(project_recycle_api.RECYCLE_ITEM_TYPE_RECYCLE_ITEM_TASK) {
			err = apiImpl.recoverIssue(sessCtx, projectItem, recycleItem.RecycleItemId)
			if err != nil {
				return nil, err
			}
		} else if recycleItem.RecycleItemType == uint32(project_recycle_api.RECYCLE_ITEM_TYPE_RECYCLE_ITEM_BUG) {
			err = apiImpl.recoverIssue(sessCtx, projectItem, recycleItem.RecycleItemId)
			if err != nil {
				return nil, err
			}
		} else if recycleItem.RecycleItemType == uint32(project_recycle_api.RECYCLE_ITEM_TYPE_RECYCLE_ITEM_TESTCASE) {
			err = apiImpl.recoverTestcase(sessCtx, projectItem, recycleItem.RecycleItemId)
			if err != nil {
				return nil, err
			}
		} else if recycleItem.RecycleItemType == uint32(project_recycle_api.RECYCLE_ITEM_TYPE_RECYCLE_ITEM_BULLETIN) {
			err = apiImpl.recoverBulletin(sessCtx, projectItem, recycleItem.RecycleItemId)
			if err != nil {
				return nil, err
			}
		} else { //entry
			err = apiImpl.recoverEntry(sessCtx, projectItem, recycleItem.RecycleItemId)
			if err != nil {
				return nil, err
			}
		}
		return &project_recycle_api.RecoverResponse{
			Code: project_recycle_api.RecoverResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	//记录事件
	go apiImpl.addRecoverFromRecycleEvent(sessionItem, projectItem, req.RecycleItemId,
		project_recycle_api.RECYCLE_ITEM_TYPE(recycleItem.RecycleItemType), title, time.Now().UnixNano()/1e6)
	return ret.(*project_recycle_api.RecoverResponse), nil
}

func (apiImpl *ProjectRecycleApiImpl) recoverIdea(ctx context.Context, projectItem *project_dao.ProjectInfoDbItem, recycleItemId string) error {
	item, err := idea_dao.IdeaRecycleDao.Get(ctx, projectItem.ProjectId, recycleItemId)
	if err != nil {
		return err
	}
	err = idea_dao.IdeaRecycleDao.Remove(ctx, projectItem.ProjectId, recycleItemId)
	if err != nil {
		return err
	}
	//检查分组是否存在
	exist, err := idea_dao.IdeaGroupDao.Exist(ctx, projectItem.ProjectId, item.IdeaGroupId)
	if err != nil {
		return err
	}
	if !exist {
		item.IdeaGroupId = projectItem.DefaultIdeaGroupId
	}

	err = idea_dao.IdeaDao.Insert(ctx, item)
	if err != nil {
		return err
	}

	//更新分组计数
	count, err := idea_dao.IdeaDao.Count(ctx, projectItem.ProjectId, &project_idea_api.ListIdeaParam{
		FilterByGroupId: true,
		GroupId:         item.IdeaGroupId,
	})
	if err != nil {
		return err
	}
	err = idea_dao.IdeaGroupDao.UpdateIdeaCount(ctx, projectItem.ProjectId, item.IdeaGroupId, count)
	if err != nil {
		return err
	}

	return nil
}

func (apiImpl *ProjectRecycleApiImpl) recoverRequirement(ctx context.Context, projectItem *project_dao.ProjectInfoDbItem, recycleItemId string) error {
	item, err := requirement_dao.RequirementRecycleDao.Get(ctx, projectItem.ProjectId, recycleItemId)
	if err != nil {
		return err
	}
	err = requirement_dao.RequirementRecycleDao.Remove(ctx, projectItem.ProjectId, recycleItemId)
	if err != nil {
		return err
	}
	err = requirement_dao.RequirementInfoDao.Insert(ctx, item)
	if err != nil {
		return err
	}
	return nil
}

func (apiImpl *ProjectRecycleApiImpl) recoverIssue(ctx context.Context, projectItem *project_dao.ProjectInfoDbItem, recycleItemId string) error {
	item, err := issue_dao.IssueRecycleDao.Get(ctx, projectItem.ProjectId, recycleItemId)
	if err != nil {
		return err
	}
	err = issue_dao.IssueRecycleDao.Remove(ctx, projectItem.ProjectId, recycleItemId)
	if err != nil {
		return err
	}
	//检查sprit
	if item.SpritId != "" {
		exist, err := project_entry_dao.EntryDao.Exist(ctx, item.SpritId, projectItem.ProjectId)
		if err != nil {
			return err
		}
		if !exist {
			item.SpritId = ""
		}
	}
	//调整其他参数
	item.DependMeCount = 0
	err = issue_dao.IssueDao.Insert(ctx, item)
	if err != nil {
		return err
	}
	return nil
}

func (apiImpl *ProjectRecycleApiImpl) recoverTestcase(ctx context.Context, projectItem *project_dao.ProjectInfoDbItem, recycleItemId string) error {
	item, err := testcase_dao.CaseRecycleDao.Get(ctx, recycleItemId, projectItem.ProjectId)
	if err != nil {
		return err
	}
	err = testcase_dao.CaseRecycleDao.Remove(ctx, recycleItemId, projectItem.ProjectId)
	if err != nil {
		return err
	}
	if item.ParentFolderId != "" {
		exist, err := testcase_dao.FolderInfoDao.Exist(ctx, item.ParentFolderId, projectItem.ProjectId)
		if err != nil {
			return err
		}
		if !exist {
			item.ParentFolderId = ""
		}
	}
	err = testcase_dao.CaseInfoDao.Insert(ctx, item)
	if err != nil {
		return err
	}
	if item.ParentFolderId != "" {
		count, err := testcase_dao.CaseInfoDao.CountSubCase(ctx, item.ParentFolderId, projectItem.ProjectId)
		if err != nil {
			return err
		}
		err = testcase_dao.FolderInfoDao.UpdateSubCaseCount(ctx, item.ParentFolderId, projectItem.ProjectId, count)
		if err != nil {
			return err
		}
	}
	return nil
}

func (apiImpl *ProjectRecycleApiImpl) recoverBulletin(ctx context.Context, projectItem *project_dao.ProjectInfoDbItem, recycleItemId string) error {
	item, err := bulletin_dao.BulletinRecycleDao.Get(ctx, recycleItemId, projectItem.ProjectId)
	if err != nil {
		return err
	}
	err = bulletin_dao.BulletinRecycleDao.Remove(ctx, recycleItemId, projectItem.ProjectId)
	if err != nil {
		return err
	}
	err = bulletin_dao.BulletinInfoDao.Insert(ctx, item)
	if err != nil {
		return err
	}
	return nil
}

func (apiImpl *ProjectRecycleApiImpl) recoverEntry(ctx context.Context, projectItem *project_dao.ProjectInfoDbItem, recycleItemId string) error {
	item, err := project_entry_dao.EntryRecycleDao.Get(ctx, recycleItemId, projectItem.ProjectId)
	if err != nil {
		return err
	}
	err = project_entry_dao.EntryRecycleDao.Remove(ctx, recycleItemId, projectItem.ProjectId)
	if err != nil {
		return err
	}
	err = project_entry_dao.EntryDao.Insert(ctx, item)
	if err != nil {
		return err
	}
	return nil
}
